<?php

namespace App\Services\TransferGoldCoin;

use App\Models\User;
use App\Models\GoldCoin;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class TransferGoldCoinRequest extends FormRequest
{
	protected $target;

	public function rules()
	{
		if (! $this->user()->isAlipayBound()) {
			fail('请先绑定支付宝账号');
		}

		if (! $this->user()->pay_code) {
			fail('请先设置交易密码');
		}

		return [
			'invite_code' => [
				'required','string',
				'min:10','max:10',
				'exists:users',
				$this->inviteCode(),
			],
			'amount' => [
				'required',
				'integer',
				'min:1',
				$this->amount()
			],
			'pay_code' => $this->paycode(false)
		];
	}

	public function inviteCode()
	{
		return function ($key, $value, $fail) {

			$target = User::where('invite_code', $value)->first();

			if (! $target) {
				return $fail('目标用户不存在');
			} elseif ($target->id == $this->user()->id) {
				return $fail('仅可向他人转出');
			} else {
				$this->target = $target;
				return true;
			}
		};
	}

	public function amount()
	{
		return function ($key, $value, $fail) {
			if ($value <= 0) {
				return $fail("请输入正确的金额");
			} elseif ($this->user()->gold_coins <= 0) {
				return $fail("可用余额不足");
			} elseif ($this->user()->gold_coins < $value) {
				return $fail("可用余额不足");
			} elseif (! $this->isLowestTransferCoinsMatched()) {
				return $fail("余额转出 {$this->allowedLowestTransferCoins()} 起");
			} else {
				return true;
			}
		};
	}

	protected function allowedLowestTransferCoins()
	{
		return GoldCoin::allowedLowestTransferCoins();
	}

	protected function isLowestTransferCoinsMatched()
	{
		return GoldCoin::isLowestTransferCoinsMatched($this->amount);
	}

	public function getTarget()
	{
		return $this->target;
	}
}
